package com.huahua.api.service.impl;

import com.huahua.api.entity.param.CurlExecuteParam;
import com.huahua.api.entity.param.CurlReplaceParam;
import com.huahua.api.entity.vo.CurlExecuteVo;
import com.huahua.api.entity.vo.CurlReplaceVo;
import com.huahua.api.service.CurlService;
import com.huahua.api.util.CurlUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@Service
public class CurlServiceImpl implements CurlService {

    @Override
    public Mono<CurlReplaceVo> replaceDomain(CurlReplaceParam param) {
        return Mono.fromCallable(() -> {
            String originalCurl = param.getCurlCommand();
            String newDomain = param.getNewDomain();

            if (!CurlUtils.isValidCurlCommand(originalCurl)) {
                throw new IllegalArgumentException("Invalid curl command format");
            }

            String originalDomain = CurlUtils.extractDomain(originalCurl);
            String newCurl = CurlUtils.replaceDomain(originalCurl, newDomain);

            CurlReplaceVo vo = new CurlReplaceVo();
            vo.setOriginalCurl(originalCurl);
            vo.setNewCurl(newCurl);
            vo.setOriginalDomain(originalDomain);
            vo.setNewDomain(newDomain);

            return vo;
        }).subscribeOn(Schedulers.boundedElastic());
    }

    @Override
    public Mono<CurlExecuteVo> executeCurl(CurlExecuteParam param) {
        return Mono.fromCallable(() -> {
            String curlCommand = param.getCurlCommand();
            Integer timeoutMs = param.getTimeoutMs();

            CurlExecuteVo vo = new CurlExecuteVo();
            vo.setCurlCommand(curlCommand);

            long startTime = System.currentTimeMillis();
            try {
                String response = CurlUtils.executeCurl(curlCommand, timeoutMs);
                long executionTime = System.currentTimeMillis() - startTime;

                vo.setResponse(response);
                vo.setSuccess(true);
                vo.setExecutionTimeMs(executionTime);
            } catch (Exception e) {
                long executionTime = System.currentTimeMillis() - startTime;
                vo.setSuccess(false);
                vo.setErrorMessage(e.getMessage());
                vo.setExecutionTimeMs(executionTime);
            }

            return vo;
        }).subscribeOn(Schedulers.boundedElastic());
    }
}